/**
 * Created by Jellyleo on 2019年12月16日
 * Copyright © 2019 jellyleo.com
 * All rights reserved.
 */
package com.jellyleo.activiti.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.jellyleo.activiti.entity.ActRuTask;
import com.jellyleo.activiti.entity.CommonVariable;
import com.jellyleo.activiti.feign.CustomerFeign;
import com.jellyleo.activiti.feign.DirectOrderFeign;
import com.jellyleo.activiti.service.ActRuTaskService;
import com.jellyleo.activiti.util.BeanUtil;
import com.woniu.dto.ActRuTaskDto;
import com.woniu.dto.DirectOrdersDto;
import com.woniu.dto.OrderbillingsUnitDto;
import com.woniu.pojo.PageParam;
import com.woniu.until.ResponseData;
import org.activiti.bpmn.model.*;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.task.DelegationState;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 功能描述:任务控制器
 *
 * @author Jelly
 * @version 1.0.0
 * @created 2019年11月19日
 */
@RestController
@RequestMapping("/task")
public class TaskController extends BaseController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CustomerFeign customerFeign;
    @Autowired
    private DirectOrderFeign directOrderFeign;


    /**
     * 功能描述:查询任务
     *
     * @param request
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */

    @Autowired
    private ActRuTaskService actRuTaskService;


    @PostMapping("/getTaskHistoryList")
    @ResponseBody
    public ResponseData<?> getTaskHistoryList(@RequestBody PageParam<ActRuTask> param) {
        return actRuTaskService.getTaskHistoryList(param);
    }

    @PostMapping("/getTaskHistoryListById")
    @ResponseBody
    public ResponseData<?> getTaskHistoryListById(@RequestBody CommonVariable commonVariable) {
        return actRuTaskService.getTaskHistoryListById(commonVariable.getId());
    }


    @PostMapping("/getTaskList")
    @ResponseBody
    public ResponseData<?> getTaskList(@RequestBody PageParam<ActRuTask> param) {
        return actRuTaskService.getTaskList(param);
    }

    @PostMapping("/getTaskListByName")
    @ResponseBody
    public ActRuTaskDto getTaskListByName(String username) {
        return actRuTaskService.getTaskListByName(username);
    }


    /**
     * 功能描述:完成任务
     *
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/complete")
    @ResponseBody
    public String complete(@RequestBody CommonVariable commonVariable) {

        String taskId = commonVariable.getId();
        Task task1 = taskService.createTaskQuery()
                .taskId(taskId)
                .singleResult();
        String processInstanceId = task1.getProcessInstanceId();
        String txt = (String) redisTemplate.opsForHash().get("customer", processInstanceId);
        OrderbillingsUnitDto customer = JSON.parseObject(txt, OrderbillingsUnitDto.class);

        if (StringUtils.isEmpty(taskId)) {
            return "param error";
        }
        Integer pass = commonVariable.getPass();
        Integer status = customer.getStatus();
        String variable = "{\"pass\": " + pass + ", \"status\": " + status + "}";
        try {
            Map<String, Object> variables = new HashMap<>();
            if (!StringUtils.isEmpty(variable)) {
//				CommonVariable variablesEntity = JSON.parseObject(variable, CommonVariable.class);
                CommonVariable variablesEntity = JSON.parseObject(variable, CommonVariable.class);
                variables = BeanUtil.beanToMap(variablesEntity);
            }
//			// 设置流程参数（单）
//			taskService.setVariable(taskId, key, value);
            // 设置流程参数（多）
            taskService.setVariables(taskId, variables);


            // 若是委托任务，请先解决委托任务
            Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
            if (DelegationState.PENDING.equals(task.getDelegationState())) {
                return "resolve delegation first";
            }
            taskService.complete(taskId);


            ExecutionEntity R = (ExecutionEntity) runtimeService
                    .createExecutionQuery().executionId(task.getExecutionId()).singleResult();
            if (R == null ){
                customerFeign.addOrderBillings(customer);
            }
            System.out.println("任务完成");
            System.out.println("任务ID:" + taskId);
            System.out.println("任务处理结果:" + variables);
            System.out.println("*****************************************************************************");
        } catch (Exception e) {
            return "fail";
        }
        return "success";
    }
    /**
     * 功能描述:完成任务
     *
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/completeOrder")
    @ResponseBody
    public String completeOrder(@RequestBody CommonVariable commonVariable) {

        String taskId = commonVariable.getId();
        Task task1 = taskService.createTaskQuery()
                .taskId(taskId)
                .singleResult();
        String processInstanceId = task1.getProcessInstanceId();
        String txt = (String) redisTemplate.opsForHash().get("order", processInstanceId);
        DirectOrdersDto directOrdersDto = JSON.parseObject(txt, DirectOrdersDto.class);

        if (StringUtils.isEmpty(taskId)) {
            return "param error";
        }
        Integer pass = commonVariable.getPass();
        String isDesignInProject = directOrdersDto.getIsDesignInProject();
        String variable = "{\"pass\": " + pass + ", \"status\": " + isDesignInProject + "}";
        try {
            Map<String, Object> variables = new HashMap<>();
            if (!StringUtils.isEmpty(variable)) {
//				CommonVariable variablesEntity = JSON.parseObject(variable, CommonVariable.class);
                CommonVariable variablesEntity = JSON.parseObject(variable, CommonVariable.class);
                variables = BeanUtil.beanToMap(variablesEntity);
            }
//			// 设置流程参数（单）
//			taskService.setVariable(taskId, key, value);
            // 设置流程参数（多）
            taskService.setVariables(taskId, variables);


            // 若是委托任务，请先解决委托任务
            Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
            if (DelegationState.PENDING.equals(task.getDelegationState())) {
                return "resolve delegation first";
            }
            taskService.complete(taskId);


            ExecutionEntity R = (ExecutionEntity) runtimeService
                    .createExecutionQuery().executionId(task.getExecutionId()).singleResult();
            if (R == null ){
                directOrderFeign.saveDirectOrder(directOrdersDto);

            }
            System.out.println("任务完成");
            System.out.println("任务ID:" + taskId);
            System.out.println("任务处理结果:" + variables);
            System.out.println("*****************************************************************************");
        } catch (Exception e) {
            return "fail";
        }
        return "success";
    }

    /**
     * 功能描述:解决委托任务
     *
     * @param request
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/resolve")
    @ResponseBody
    public String resolve(HttpServletRequest request, HttpServletResponse response) {

        String taskId = request.getParameter("taskid");
        String variable = request.getParameter("variable");

        if (StringUtils.isEmpty(taskId)) {
            return "param error";
        }

        try {
            Map<String, Object> variables = new HashMap<>();
            if (!StringUtils.isEmpty(variable)) {
                CommonVariable variablesEntity = JSON.parseObject(variable, CommonVariable.class);
                variables = BeanUtil.beanToMap(variablesEntity);
            }
//			// 设置流程参数（单）
//			taskService.setVariable(taskId, key, value);
            // 设置流程参数（多）
            taskService.setVariables(taskId, variables);

            // 根据taskId提取任务
            Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
            if (task.getOwner() != null && !task.getOwner().equals("null")) {
                DelegationState delegationState = task.getDelegationState();
                if (delegationState.equals(DelegationState.RESOLVED)) {
                    System.out.println("此委托任务已是完结状态");
                } else if (delegationState.equals(DelegationState.PENDING)) {
                    // 如果是委托任务需要做处理
                    taskService.resolveTask(taskId, variables);
                } else {
                    System.out.println("此任务不是委托任务");
                }
            }
            System.out.println("委托任务处理完毕");
            System.out.println("*****************************************************************************");
        } catch (Exception e) {
            return "fail";
        }
        return "success";
    }

}
